<?php
namespace wxapp\aes;

class Wxpay{
    public static function unifiedOrder($params, $timeOut = 6){       
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$xml = self::toXml($params);		
		$response = self::postXmlCurl($xml, $url, false, $timeOut);		
        return $response;
	}
	
	public static function microOrder($params, $timeOut = 6){       
        $url = 'https://api.mch.weixin.qq.com/pay/micropay';
		$xml = self::toXml($params);		
		$response = self::postXmlCurl($xml, $url, false, $timeOut);		
        return $response;
	}
	
	public static function queryMicroOrder($params, $timeOut = 6){       
        $url = 'https://api.mch.weixin.qq.com/pay/orderquery';
		$xml = self::toXml($params);		
		$response = self::postXmlCurl($xml, $url, false, $timeOut);		
        return $response;
	}
	
	public static function refundOrder($params, $timeOut = 6){       
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
		$xml = self::toXml($params);		
		$response = self::postXmlCurl($xml, $url, true, $timeOut);		
        return $response;
    }

    private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
	{		
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
				
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		if($useCert == true){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, EXTEND_PATH."wxapp/cert/apiclient_cert.pem");
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, EXTEND_PATH.'wxapp/cert/apiclient_key.pem');
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		} else { 
			$error = curl_errno($ch);
			curl_close($ch);
			return $error;
		}
	}

	public static function ToXml($data)
	{
		$xml = "<xml>";
    	foreach ($data as $key=>$val)
    	{
    		if (is_numeric($val)){
    			$xml.="<".$key.">".$val."</".$key.">";
    		}else{
    			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    		}
        }
        $xml.="</xml>";
        return $xml; 
	}

	public static function FromXml($xml)
	{			
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
		return $data;
	}
}